//
//  SXPHTTPClient.swift
//  weibo
//
//  Created by shixinPeng on 16/3/13.
//  Copyright © 2016年 shixinPeng. All rights reserved.
//

import UIKit
import AFNetworking

 /// 网络请求的枚举
enum resquestMethod: String{
    case GET = "GET"
    case POST = "POST"
}

class SXPHTTPClient: AFHTTPSessionManager {
 /// 网络帮助工具的单例
    static let shareInstance: SXPHTTPClient = SXPHTTPClient()
    
    ///  网络请求
    ///
    ///  - parameter method:    网络请求的方法,是一个枚举
    ///  - parameter URLString: 发送网络请求的url
    ///  - parameter params:    网络请求的数据
    ///  - parameter success:   成功之后的回调
    ///  - parameter failure:   时候的回调
    func request(method: resquestMethod, URLString: String, params:[String: AnyObject]?,success:((JSON: [String: AnyObject]?) -> ()),failure:((error: NSError) -> ())){
        
        //请求成功的回调
        let successClosure = {(task: NSURLSessionDataTask, json:AnyObject?) -> () in
            
            let dic = json as? [String: AnyObject]
            
            success(JSON: dic)
        }
        //失败之后的回调
        let failureClosure = {(task:NSURLSessionDataTask?, error: NSError) ->() in
            printLog(error)
            
        }
        
        
        if method == .GET{//"GET"请求
            self.GET(URLString, parameters: params, progress: nil, success: successClosure, failure: failureClosure)
            
        }else if method == .POST{
            self.POST(URLString, parameters: params, progress: nil, success: successClosure, failure: failureClosure)
        }
 
    }
    //上传数据的方法
    func upload(URLSting: String,params: [String: AnyObject]?,data: NSData, success:((restult: [String: AnyObject]?) -> ()), failure:((error:NSError) -> ()) ){
        
        POST(URLSting, parameters: params, constructingBodyWithBlock: { (formData) -> Void in
            
            
            formData.appendPartWithFileData(data, name: "pic", fileName: "xx", mimeType: "image/jepg")
           
            }, progress: nil, success: { (_, result) -> Void in
                
                if let resultDict = result as? [String: AnyObject]{
                    success(restult: resultDict)
                }else{
                    failure(error: NSError(domain: "demain", code: 404, userInfo: ["test":"test"]))
                }
                
                
            }) { (_, error) -> Void in
                failure(error: error)
        }
        
    } 
}
